package com.kun.framework.core.config;

import com.kun.framework.core.exception.BizException;
import javafx.scene.web.WebView;

import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

/**
 * {@link WebView}的网络配置类
 * 主要解决程序打包成exe后，{@link WebView}组件无法访问网站问题
 *
 * @author gzc
 * @since 2024/9/21
 **/
public class WebViewConfiguration {
    /**
     * 初始化
     */
    public static void init() {
        try {
            // 安装完全信任的信任管理器
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null,
                    new TrustManager[]{new KunX509TrustManager()},
                    new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // 创建完全信任的主机名验证器
            HostnameVerifier allHostsValid = (hostname, session) -> true;
            // 安装完全信任的主机验证程序
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        } catch (Exception e) {
            throw new BizException("初始化信任管理器失败", e);
        }
    }

    /**
     * 自定义信任管理器
     */
    private static class KunX509TrustManager implements X509TrustManager {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    }
}
